require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const authRoutes = require('./routes/auth');
const writerRoutes = require('./routes/writer');
const workRoutes = require('./routes/work');
const quoteRoutes = require('./routes/quote');
const userRoutes = require('./routes/user');

const app = express();

app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 设置字符编码
app.use((req, res, next) => {
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  next();
});

// 静态文件服务，用于访问上传的图片
app.use('/img', express.static(path.join(__dirname, '../img')));

app.use('/api', authRoutes);
app.use('/api/writers', writerRoutes);
app.use('/api/works', workRoutes);
app.use('/api/quotes', quoteRoutes);
app.use('/api/user', userRoutes);

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
}); 

const dotenv = require('dotenv');
dotenv.config();